import React, { Component } from "react"

const SelectHoc = WrappedComponent => {

  class hoc extends Component {

    constructor(props) {
      super(props);
      const { selectedKeys = [], targetKeys = [] } = props;
      this.state = {
        sourceSelectedKeys: selectedKeys.filter(key => !targetKeys.includes(key)),
        targetSelectedKeys: selectedKeys.filter(key => targetKeys.includes(key)),
      };
    }

    componentWillReceiveProps(nextProps) {
      if (nextProps.selectedKeys) {
        const targetKeys = nextProps.targetKeys || [];
        this.setState({
          sourceSelectedKeys: nextProps.selectedKeys.filter(key => !targetKeys.includes(key)),
          targetSelectedKeys: nextProps.selectedKeys.filter(key => targetKeys.includes(key)),
        });
      }
    }

    setSource = (name, array) => {
      this.setState({ [name]: array })
    };

    render() {
      const { sourceSelectedKeys, targetSelectedKeys } = this.state;
      return (
        <WrappedComponent
          sourceSelectedKeys={sourceSelectedKeys}
          targetSelectedKeys={targetSelectedKeys}
          setSource={this.setSource}
          {...this.props}
        />
      )
    }
  }

  return hoc
};

export default SelectHoc
